package com.railway.switchs.utils;

import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName IpAddressUtil
 * @Author 魏梓晟
 * @Version 1.0
 **/
@Slf4j
public class IpAddressUtil {

    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值
     * @return ip
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if( ip.indexOf(",")!=-1 ){
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 通过ip获取地理位置
     * 实现：
     *     通过访问http://ip.chinaz.com获取页面，再抓取页面中的地理位置
     * @param ipAddress
     * @return
     */
    public static String getAddressByIp(String ipAddress){
        String addressStr = "";
        try{
            Document doc = null;
            doc = Jsoup.connect("http://ip.chinaz.com/?ip="+ipAddress).get();

            // dom解析获得指定元素
            Elements datas = doc.getElementsByClass("Whwtdhalf w50-0");

            if(StringUtil.isEmpty(datas)){
                addressStr = "异常获取";
            }else{
                Element element = datas.last();
                log.info("抓取的地理位置标签:"+element.toString());
                //根据规则获取内容
                addressStr = element.text();
                log.info("抓取的地理位置:"+addressStr);
            }
        }catch (Exception e){
            log.error("通过ip获取地理位置异常",e);
            addressStr = "异常获取";
        }
        return addressStr;
    }
}
